window.onload = function() {
	var	$ = function(id) {return document.getElementById(id)};

	var	tbl = $('placements'),
		allTests = $('all-tests'),
		startButton = $('start-button'),
		allCB = tbl.getElementsByTagName('input'),
		stopButton = $('stop-button'),
		browserInput = $('browser'),
		versionInput = $('version'),
		countrySelect = $('country'),
		browserSpan = $('browser-span'),
		saveForm = $('save-results'),
		scoresInput = $('scores');

	function getBrowser() {
		var browsers = {'chrome': {name: 'Chrome', version: /chrome\/([0-9\.]*)/}, 
						'konqueror': {name: 'Konqueror', version: /konqueror\/([0-9\.]*)/},
						'webkit': {name: 'Safari', version: /version\/([0-9\.]*)/},
						'presto': {name: 'Opera', version: /opera\/([0-9\.]*)/},
						'gecko': {name: 'FireFox', version: /firefox\/([0-9\.]*)/},
						'msie': {name: 'Internet Explorer', version: /msie\s([0-9\.]*)/}},
			ua = navigator.userAgent.toLowerCase(),
			browser = 'Unknown',
			version = 'x.x';
		
		for (var i in browsers) {
			if (ua.indexOf(i) !== -1) {
				var m = ua.match(browsers[i].version);
				if (m != null)
					version = m.pop();
				
				browser = browsers[i].name;

				break;
			}
		}
		
		return {
			display: browser + ' ' + version,
			id: i,
			version: version
		};
	}
		
	function hasClassName(element, className) {
		var elementClassName = element.className;

		return (elementClassName.length > 0 && (elementClassName == className ||
			new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
	}
		
	function getCBByClassName(classname) {
		var ret = []
		for (var i = 0, len = allCB.length; i < len; i++)
			if (hasClassName(allCB[i], classname))
				ret.push(allCB[i]);
				
		return ret;
	}

	function toggleCB(classname, value) {
		if (typeof classname == 'string') 
			var elements = getCBByClassName(classname);
		else
			var elements = classname;
		
		for (var i = 0, len = elements.length; i < len; i++)
			elements[i].checked = value;
	}
	
	var rowcols = {	'cdn': getCBByClassName('cdn'),
					'framework': getCBByClassName('framework')},
		placementCB = getCBByClassName('placement');

	allTests.onclick = function() {
		toggleCB(placementCB, this.checked);
		toggleCB(rowcols['cdn'], false);
		toggleCB(rowcols['framework'], false);
	}

	for (var ctype in rowcols) {
		var els = rowcols[ctype]
		for (var i = 0, len = els.length; i < len; i++) {
			els[i].onclick = function() {
				if (allTests.checked) {
					allTests.checked = false;
					toggleCB(placementCB, false);
				}
				
				toggleCB(this.className + '-' + this.id, this.checked);
			}
		}
	}

	var taskList = [],
		results;

	startButton.onclick = function() {
		results = {};
		this.style.display = 'none';
		stopButton.style.display = 'inline';
		saveForm.style.display = 'none';
		
		for (var i = 0, len = placementCB.length; i < len; i++) {
			placementCB[i].style.display = 'none';
			var span = placementCB[i].parentNode.getElementsByTagName('span')[0];

			if (placementCB[i].checked) {
				taskList.push(placementCB[i].value);
				span.className = "";
				span.innerHTML = '';
			}
			else {
				span.className = "na";
				span.innerHTML = 'n/a';
			}
		}
		testRunner();
	}

	stopButton.onclick = function() {
		this.style.display = 'none';
		startButton.style.display = 'inline';

		taskList = [];
		clearTimeout(timer);
		
		if (!testIsRunning)
			finalizeTests(true);
	}
	
	var timer = null,
		testFrame = false,
		testIsRunning = false;
		
	function removeIframe() {
		if (testFrame) {
			try {
				testFrame.parentNode.removeChild(testFrame);
			} catch(e) {};
			testFrame = false;
		}
	}

	var testRunner = function () {
		var task = taskList.shift();
		if (!task)
			return;
		
		testIsRunning = true;
		removeIframe();
			
		testFrame = document.createElement("iframe");
		testFrame.src = '/test/' + encodeURIComponent(task);
		
		document.body.appendChild(testFrame);
	}
	
	function finalizeTests(dontStore) {
		removeIframe();
		
		for (var i = 0, len = placementCB.length; i < len; i++)
			placementCB[i].style.display = 'inline';

		startButton.style.display = 'inline';
		stopButton.style.display = 'none';
		saveForm.style.display = 'block';
		
		var res = [];
		for (i in results)
			res.push(i + '=' + results[i]);
		scoresInput.value = res.join(';');
	}
	
	window.logResults = function(url, time) {
		testIsRunning = false;

		var cell = false;
		for (var i = 0, len = placementCB.length; i < len; i++)
			if (placementCB[i].value == url) {
				cell = placementCB[i].parentNode.getElementsByTagName('span')[0];
				break;
			}
		
		if (cell) {
			cell.innerHTML = time + 'ms.'
			
			results[url] = time;
		}
		
		if (taskList.length > 0)
			timer = setTimeout(testRunner, 250);
		else
			finalizeTests();
	}
	
	try {
		var country = geoip_country_code();
	} catch (e) {}
	
	var browser = getBrowser();
		
	browserSpan.innerHTML = browser.display;
	browserInput.value = browser.id;
	versionInput.value = browser.version;
	
	for (var i = 0, len = countrySelect.length; i < len; i++) 
		if (countrySelect[i].value == country) {
			countrySelect[i].selected = true;
			break;
		}
}